document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const apiUrlInput = document.getElementById('api-url');
            const apiKeyInput = document.getElementById('api-key');
            const modelTypeSelect = document.getElementById('model-type');
            const modelSelect = document.getElementById('model');
            const modelInfo = document.getElementById('model-info');
            const modelContext = document.getElementById('model-context');
            const modelOutput = document.getElementById('model-output');
            const modelFree = document.getElementById('model-free');
            const temperatureInput = document.getElementById('temperature');
            const temperatureValue = document.getElementById('temperature-value');
            const maxTokensInput = document.getElementById('max-tokens');
            const streamResponseCheckbox = document.getElementById('stream-response');
            const saveConfigButton = document.getElementById('save-config');
            const testApiButton = document.getElementById('test-api');
            const apiStatus = document.getElementById('api-status');
            const chatMessages = document.getElementById('chat-messages');
            const messageInput = document.getElementById('message-input');
            const sendButton = document.getElementById('send-button');
            const typingIndicator = document.getElementById('typing-indicator');
            const addRoleButton = document.getElementById('add-role');
            const roleButtonsContainer = document.getElementById('role-buttons');
            const roleEditor = document.getElementById('role-editor');
            const roleNameInput = document.getElementById('role-name');
            const rolePromptInput = document.getElementById('role-prompt');
            const saveRoleButton = document.getElementById('save-role');
            const deleteRoleButton = document.getElementById('delete-role');
            const currentRoleDisplay = document.getElementById('current-role-display');
            
            // 初始化Markdown解析器
            const md = new markdownit({
                html: true,
                linkify: true,
                typographer: true,
                highlight: function (str, lang) {
                    // 检查highlight.js是否可用
                    if (window.hljs && lang && hljs.getLanguage && hljs.highlight) {
                        try {
                            return hljs.highlight(str, { language: lang }).value;
                        } catch (e) {
                            console.warn('代码高亮失败:', e);
                        }
                    }
                    return ''; // 使用默认转义
                }
            });
            
            // 渲染数学公式的函数
            function renderMathInElement(element) {
                try {
                    if (window.MathJax) {
                        // 使用MathJax渲染数学公式
                        MathJax.typesetElement(element);
                    }
                } catch (error) {
                    console.warn('MathJax渲染失败，可能需要手动触发:', error);
                }
            }

            // 模型信息数据库
            const modelDatabase = {
                // 文本模型
                'glm-4.6': { context: '200K', output: '128K', free: false },
                'glm-4.5': { context: '128K', output: '96K', free: false },
                'glm-4.5-x': { context: '128K', output: '96K', free: false },
                'glm-4.5-air': { context: '128K', output: '96K', free: false },
                'glm-4.5-airx': { context: '128K', output: '96K', free: false },
                'glm-4-plus': { context: '128K', output: '4K', free: false },
                'glm-4-air-250414': { context: '128K', output: '16K', free: false },
                'glm-4-long': { context: '1M', output: '4K', free: false },
                'glm-4-airx': { context: '8K', output: '4K', free: false },
                'glm-4-flashx-250414': { context: '128K', output: '16K', free: false },
                'glm-4.5-flash': { context: '128K', output: '96K', free: true },
                'glm-4-flash-250414': { context: '128K', output: '16K', free: true },
                
                // 视觉模型
                'glm-4.5v': { context: '64K', output: '16K', free: false },
                'glm-4.1v-thinking-flashx': { context: '64K', output: '16K', free: false },
                'glm-4v-plus-0111': { context: '16K', output: '动态计算', free: false },
                'glm-4.1v-thinking-flash': { context: '64K', output: '16K', free: true },
                'glm-4v-flash': { context: '16K', output: '动态计算', free: true }
            };

            // 角色管理变量
            let roles = {};
            let currentRoleId = null;
            let editingRoleId = null;

            // 温度滑块值显示
            temperatureInput.addEventListener('input', function() {
                temperatureValue.textContent = this.value;
            });

            // 模型类型切换
            modelTypeSelect.addEventListener('change', function() {
                const modelType = this.value;
                const visionModels = document.querySelectorAll('.vision-model');
                
                if (modelType === 'vision') {
                    // 显示视觉模型，隐藏文本模型
                    visionModels.forEach(group => group.style.display = 'block');
                    // 选择第一个视觉模型
                    const firstVisionModel = document.querySelector('.vision-model option');
                    if (firstVisionModel) {
                        modelSelect.value = firstVisionModel.value;
                        updateModelInfo(firstVisionModel.value);
                    }
                } else {
                    // 显示文本模型，隐藏视觉模型
                    visionModels.forEach(group => group.style.display = 'none');
                    // 选择默认文本模型
                    modelSelect.value = 'glm-4.5-flash';
                    updateModelInfo('glm-4.5-flash');
                }
            });

            // 模型选择变化时更新信息
            modelSelect.addEventListener('change', function() {
                updateModelInfo(this.value);
            });

            // 更新模型信息显示
            function updateModelInfo(modelId) {
                const model = modelDatabase[modelId];
                if (model) {
                    modelContext.textContent = `上下文: ${model.context}`;
                    modelOutput.textContent = `最大输出: ${model.output}`;
                    
                    if (model.free) {
                        modelFree.style.display = 'inline-block';
                    } else {
                        modelFree.style.display = 'none';
                    }
                    
                    modelInfo.classList.add('active');
                } else {
                    modelInfo.classList.remove('active');
                }
            }

            // 角色管理功能
            addRoleButton.addEventListener('click', function() {
                const roleId = 'role_' + Date.now();
                const roleName = '角色' + (Object.keys(roles).length + 1);
                
                roles[roleId] = {
                    id: roleId,
                    name: roleName,
                    prompt: '角色：' + roleName + '\n性格：\n说话风格：\n背景：'
                };
                
                saveRoles();
                renderRoleButtons();
                
                // 自动打开新角色的编辑器
                editRole(roleId);
            });

            saveRoleButton.addEventListener('click', function() {
                if (!editingRoleId) return;
                
                const name = roleNameInput.value.trim();
                const prompt = rolePromptInput.value.trim();
                
                if (!name) {
                    alert('请输入角色名称');
                    return;
                }
                
                roles[editingRoleId].name = name;
                roles[editingRoleId].prompt = prompt;
                
                saveRoles();
                renderRoleButtons();
                
                // 关闭编辑器
                roleEditor.classList.remove('active');
                editingRoleId = null;
            });

            deleteRoleButton.addEventListener('click', function() {
                if (!editingRoleId) return;
                
                if (confirm('确定要删除这个角色吗？')) {
                    delete roles[editingRoleId];
                    
                    // 如果删除的是当前角色，清除当前角色
                    if (currentRoleId === editingRoleId) {
                        currentRoleId = null;
                        updateCurrentRoleDisplay();
                    }
                    
                    saveRoles();
                    renderRoleButtons();
                    
                    // 关闭编辑器
                    roleEditor.classList.remove('active');
                    editingRoleId = null;
                }
            });

            function editRole(roleId) {
                const role = roles[roleId];
                if (!role) return;
                
                editingRoleId = roleId;
                roleNameInput.value = role.name;
                rolePromptInput.value = role.prompt;
                roleEditor.classList.add('active');
            }

            function selectRole(roleId) {
                currentRoleId = roleId;
                updateCurrentRoleDisplay();
                renderRoleButtons();
                
                // 添加系统消息
                addMessage('system', `已切换到角色: ${roles[roleId].name}`);
            }

            function updateCurrentRoleDisplay() {
                if (currentRoleId && roles[currentRoleId]) {
                    currentRoleDisplay.textContent = `当前角色: ${roles[currentRoleId].name}`;
                } else {
                    currentRoleDisplay.textContent = '未选择角色';
                }
            }

            function renderRoleButtons() {
                roleButtonsContainer.innerHTML = '';
                
                Object.values(roles).forEach(role => {
                    const button = document.createElement('button');
                    button.className = 'role-button';
                    button.textContent = role.name;
                    button.dataset.roleId = role.id;
                    
                    if (role.id === currentRoleId) {
                        button.classList.add('active');
                    }
                    
                    button.addEventListener('click', function() {
                        if (this.classList.contains('active')) {
                            // 如果已经是当前角色，则编辑
                            editRole(role.id);
                        } else {
                            // 否则选择这个角色
                            selectRole(role.id);
                        }
                    });
                    
                    roleButtonsContainer.appendChild(button);
                });
            }

            function saveRoles() {
                localStorage.setItem('zhipuAiRoles', JSON.stringify(roles));
            }

            function loadRoles() {
                const savedRoles = localStorage.getItem('zhipuAiRoles');
                if (savedRoles) {
                    roles = JSON.parse(savedRoles);
                    renderRoleButtons();
                }
            }

            // 从localStorage加载保存的配置
            function loadConfig() {
                const savedConfig = localStorage.getItem('zhipuAiConfig');
                if (savedConfig) {
                    const config = JSON.parse(savedConfig);
                    apiUrlInput.value = config.apiUrl || 'https://open.bigmodel.cn/api/paas/v4/chat/completions';
                    apiKeyInput.value = config.apiKey || '';
                    modelTypeSelect.value = config.modelType || 'text';
                    modelSelect.value = config.model || 'glm-4.5-flash';
                    temperatureInput.value = config.temperature || 1.0;
                    temperatureValue.textContent = config.temperature || 1.0;
                    maxTokensInput.value = config.maxTokens || 1024;
                    streamResponseCheckbox.checked = config.streamResponse || false;
                    currentRoleId = config.currentRoleId || null;
                    
                    // 触发模型类型变化以正确显示模型
                    modelTypeSelect.dispatchEvent(new Event('change'));
                    updateModelInfo(config.model || 'glm-4.5-flash');
                    updateCurrentRoleDisplay();
                } else {
                    // 初始化默认模型信息
                    updateModelInfo('glm-4.5-flash');
                }
            }

            // 保存配置到localStorage
            saveConfigButton.addEventListener('click', function() {
                const config = {
                    apiUrl: apiUrlInput.value,
                    apiKey: apiKeyInput.value,
                    modelType: modelTypeSelect.value,
                    model: modelSelect.value,
                    temperature: parseFloat(temperatureInput.value),
                    maxTokens: parseInt(maxTokensInput.value),
                    streamResponse: streamResponseCheckbox.checked,
                    currentRoleId: currentRoleId
                };
                
                localStorage.setItem('zhipuAiConfig', JSON.stringify(config));
                
                apiStatus.textContent = '配置已保存！';
                apiStatus.className = 'api-status success';
                
                setTimeout(() => {
                    apiStatus.style.display = 'none';
                }, 3000);
            });

            // 测试API连接
            testApiButton.addEventListener('click', async function() {
                if (!apiKeyInput.value) {
                    apiStatus.textContent = '请输入API密钥';
                    apiStatus.className = 'api-status error';
                    return;
                }
                
                testApiButton.disabled = true;
                testApiButton.textContent = '测试中...';
                
                try {
                    const response = await fetch(apiUrlInput.value, {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${apiKeyInput.value}`,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            model: modelSelect.value,
                            messages: [
                                {
                                    role: 'user',
                                    content: '测试连接'
                                }
                            ],
                            temperature: parseFloat(temperatureInput.value),
                            max_tokens: parseInt(maxTokensInput.value),
                            stream: false
                        })
                    });
                    
                    if (response.ok) {
                        apiStatus.textContent = 'API连接成功！';
                        apiStatus.className = 'api-status success';
                    } else {
                        const errorData = await response.json();
                        apiStatus.textContent = `连接失败: ${errorData.error?.message || response.statusText}`;
                        apiStatus.className = 'api-status error';
                    }
                } catch (error) {
                    apiStatus.textContent = `连接错误: ${error.message}`;
                    apiStatus.className = 'api-status error';
                } finally {
                    testApiButton.disabled = false;
                    testApiButton.textContent = '测试连接';
                    
                    setTimeout(() => {
                        apiStatus.style.display = 'none';
                    }, 5000);
                }
            });

            // 发送消息
            sendButton.addEventListener('click', sendMessage);
            messageInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            async function sendMessage() {
                const message = messageInput.value.trim();
                if (!message) return;
                
                if (!apiKeyInput.value) {
                    apiStatus.textContent = '请先配置API密钥';
                    apiStatus.className = 'api-status error';
                    apiStatus.style.display = 'block';
                    return;
                }
                
                // 添加用户消息到聊天区域
                addMessage('user', message);
                messageInput.value = '';
                sendButton.disabled = true;
                
                // 显示打字指示器
                typingIndicator.style.display = 'block';
                chatMessages.scrollTop = chatMessages.scrollHeight;
                
                try {
                    const messages = getConversationHistory();
                    
                    // 如果有当前角色，将角色提示作为系统消息插入
                    if (currentRoleId && roles[currentRoleId]) {
                        // 检查是否已经有系统消息，如果没有则添加
                        const hasSystemMessage = messages.some(msg => msg.role === 'system');
                        if (!hasSystemMessage) {
                            messages.unshift({
                                role: 'system',
                                content: `请按照以下角色设定进行对话：\n${roles[currentRoleId].prompt}`
                            });
                        }
                    }
                    
                    const config = {
                        model: modelSelect.value,
                        messages: messages,
                        temperature: parseFloat(temperatureInput.value),
                        max_tokens: parseInt(maxTokensInput.value),
                        stream: streamResponseCheckbox.checked
                    };
                    
                    if (streamResponseCheckbox.checked) {
                        await handleStreamResponse(config);
                    } else {
                        await handleRegularResponse(config);
                    }
                } catch (error) {
                    addMessage('assistant', `抱歉，发生错误: ${error.message}`);
                } finally {
                    typingIndicator.style.display = 'none';
                    sendButton.disabled = false;
                }
            }

            // 获取对话历史
            function getConversationHistory() {
                const messages = [];
                const messageElements = document.querySelectorAll('.message');
                
                messageElements.forEach(element => {
                    if (element.classList.contains('user')) {
                        // 用户消息直接获取textContent
                        let content = element.querySelector('.message-content').textContent;
                        // 移除角色标识
                        content = content.replace(/^用户/, '').trim();
                        messages.push({
                            role: 'user',
                            content: content
                        });
                    } else if (element.classList.contains('assistant')) {
                        // AI消息需要获取原始内容（可能包含Markdown格式）
                        let content = element.querySelector('.message-content').textContent;
                        // 移除角色标识
                        content = content.replace(/^(AI助手|.+?)$/, '').trim();
                        if (!content.includes('欢迎使用角色扮演AI对话系统') && 
                            !content.includes('已切换到角色')) {
                            messages.push({
                                role: 'assistant',
                                content: content
                            });
                        }
                    } else if (element.classList.contains('system')) {
                        // 系统消息直接获取textContent
                        let content = element.querySelector('.message-content').textContent;
                        // 移除角色标识
                        content = content.replace(/^系统/, '').trim();
                        messages.push({
                            role: 'system',
                            content: content
                        });
                    }
                });
                
                return messages;
            }

            // 处理常规响应
            async function handleRegularResponse(config) {
                const response = await fetch(apiUrlInput.value, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${apiKeyInput.value}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(config)
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error?.message || 'API请求失败');
                }
                
                const data = await response.json();
                const content = data.choices[0].message.content;
                addMessage('assistant', content);
            }

            // 处理流式响应
            async function handleStreamResponse(config) {
                const response = await fetch(apiUrlInput.value, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${apiKeyInput.value}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(config)
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error?.message || 'API请求失败');
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullContent = '';
                let assistantMessage = addMessage('assistant', '');
                let lastRenderTime = 0;
                const renderInterval = 500; // 每500毫秒重新渲染一次，避免过于频繁的更新
                
                // 渲染流式内容的函数
                function renderStreamContent() {
                    try {
                        // 获取内容容器（移除roleDiv后的部分）
                        const contentContainer = assistantMessage.querySelector('.message-content');
                        if (contentContainer) {
                            // 保存roleDiv
                            const roleDiv = contentContainer.querySelector('.message-role');
                            
                            // 清空内容容器并重新添加roleDiv
                            contentContainer.innerHTML = '';
                            contentContainer.appendChild(roleDiv);
                            
                            // 渲染Markdown
                            const htmlContent = md.render(fullContent);
                            contentContainer.innerHTML += htmlContent;
                            
                            // 渲染数学公式
                            renderMathInElement(contentContainer);
                            
                            // 代码高亮
                                if (window.hljs && hljs.highlightElement) {
                                    contentContainer.querySelectorAll('pre code').forEach((block) => {
                                        try {
                                            hljs.highlightElement(block);
                                        } catch (e) {
                                            console.warn('代码高亮失败:', e);
                                        }
                                    });
                                }
                        }
                    } catch (error) {
                        console.error('流式内容渲染错误:', error);
                    }
                }
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    
                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ') && line !== 'data: [DONE]') {
                            try {
                                const data = JSON.parse(line.substring(6));
                                if (data.choices[0].delta.content) {
                                    fullContent += data.choices[0].delta.content;
                                    
                                    // 控制渲染频率
                                    const now = Date.now();
                                    if (now - lastRenderTime > renderInterval) {
                                        renderStreamContent();
                                        lastRenderTime = now;
                                    }
                                    
                                    chatMessages.scrollTop = chatMessages.scrollHeight;
                                }
                            } catch (e) {
                                // 忽略解析错误
                            }
                        }
                    }
                }
                
                // 确保最后一次内容也被渲染
                renderStreamContent();
            }

            // 添加消息到聊天区域
            function addMessage(role, content) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${role}`;
                
                const messageContent = document.createElement('div');
                messageContent.className = 'message-content';
                
                const roleDiv = document.createElement('div');
                roleDiv.className = 'message-role';
                
                if (role === 'user') {
                    roleDiv.textContent = '用户';
                    // 用户消息保持原样显示
                    messageContent.appendChild(roleDiv);
                    messageContent.appendChild(document.createTextNode(content));
                } else if (role === 'assistant') {
                    roleDiv.textContent = currentRoleId && roles[currentRoleId] ? roles[currentRoleId].name : 'AI助手';
                    messageContent.appendChild(roleDiv);
                    
                    try {
                        // 对AI回复进行Markdown解析
                        const htmlContent = md.render(content);
                        messageContent.innerHTML += htmlContent;
                        
                        // 渲染数学公式
                        setTimeout(() => {
                            renderMathInElement(messageContent);
                            // 重新高亮代码块
                            if (window.hljs) {
                                messageContent.querySelectorAll('pre code').forEach((block) => {
                                    hljs.highlightElement(block);
                                });
                            }
                        }, 0);
                    } catch (error) {
                        console.error('Markdown解析错误:', error);
                        // 解析失败时降级为纯文本显示
                        messageContent.appendChild(document.createTextNode(content));
                    }
                } else if (role === 'system') {
                    roleDiv.textContent = '系统';
                    // 系统消息保持原样显示
                    messageContent.appendChild(roleDiv);
                    messageContent.appendChild(document.createTextNode(content));
                }
                
                messageDiv.appendChild(messageContent);
                chatMessages.appendChild(messageDiv);
                
                chatMessages.scrollTop = chatMessages.scrollHeight;
                
                return messageDiv;
            }

            // 初始化：加载保存的配置和角色
            loadConfig();
            loadRoles();
        });